package com.example.demo.controller;

import com.example.demo.entity.BaseResponse;
import com.example.demo.entity.ProductEntity;
import com.example.demo.entity.ResultBody;
import com.example.demo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class ProductController {
    @Autowired
    ProductService productService;

    @RequestMapping("/getProduct")
    public ProductEntity getProduct(int id) {
        return new ProductEntity();
    }

    @RequestMapping("/saveProduct")
    @ResponseBody
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public ResultBody saveProduct(ProductEntity product) {
        System.out.println(product.toString());
        if (productService.saveProduct(product)) {
            return new ResultBody(0, "success");
        } else {
            System.out.println("失败");
            return new ResultBody(1, "fail");
        }
    }

    @RequestMapping("/delProduct")
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public ResultBody delProduct(int id) {
        if (productService.delProduct(id)) {
            return new ResultBody(0, "success");
        } else {
            return new ResultBody(1, "fail");
        }
    }

    @RequestMapping("/listProduct")
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public BaseResponse<ProductEntity> listProduct(ProductEntity product) {
        product.setStart((product.getPage() - 1) * product.getLimit());
        List<ProductEntity> productList = productService.findAll(product);
        int count = productService.getCount(product);
        return new BaseResponse<ProductEntity>(0, "success",
                count, productList);
    }
}
